import json
import os
import uuid

from rest_framework.decorators import api_view
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth import get_user_model, authenticate
from rest_framework_simplejwt.tokens import RefreshToken, AccessToken
from .serializers import UserSerializer, LoginSerializer
from user.models import User
from user.serializers import UserSerializer
from django.core.files.storage import default_storage


# User = get_user_model()


class RegisterView(APIView):
    """注册视图：所有逻辑在视图中处理"""

    def post(self, request):
        # 获取并验证数据
        username = request.data.get('username')
        password = request.data.get('password')
        password2 = request.data.get('repassword')

        # 简单验证
        if not all([username, password, password2]):
            return Response({'msg': '用户名、密码不能为空'}, status=status.HTTP_400_BAD_REQUEST)
        if password != password2:
            return Response({'msg': '两次密码不一致'}, status=status.HTTP_400_BAD_REQUEST)
        if User.objects.filter(username=username).exists():
            return Response({'msg': '用户名已存在'}, status=status.HTTP_400_BAD_REQUEST)

        # 创建用户
        user = User.objects.create_user(
            username=username,
            password=password,
            email=request.data.get('email', ''),
            phone=request.data.get('phone', ''),
            nickname=request.data.get('nickname', '')
        )
        return Response({
            'msg': '注册成功',
            'code': 200,
            'reslut': {
                'id': user.id
            }
        },
            status=status.HTTP_201_CREATED)

    # class LoginView(APIView):
    """登录视图：返回JWT令牌"""


@api_view(['POST'])
def login(request):
    try:
        print(request.POST)
        username = request.POST.get('username')
        password = request.POST.get('password')
        # data = json.loads(request.POST.dict())
        # username = data.get('username')
        # password = data.get('password')
        print(username, password)

        # 方法1：使用 authenticate（推荐）
        user = authenticate(request, username=username, password=password)

        # 生成令牌
        refresh = RefreshToken.for_user(user)
        if user is not None:
            # 密码正确，用户已认证
            return Response({
                'msg': '登录成功',
                'state': 200,
                'data': {
                    'token': str(refresh.access_token),
                    # 'refresh': str(refresh),
                    'id': user.id,
                    'avatar': str(user.avatar),
                    'name': str(user.username),
                    'brokerage': str(user.brokerage),
                }
            })
        else:
            # 用户名或密码错误
            return Response({
                'msg': '用户名密码错误'
            }, status=401)

        # return Response({
        #
        # })
    except Exception as e:
        return Response({
            'msg': f'服务器错误{e}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class LogoutView(APIView):

    def post(self, request):
        access_token = request.POST.get('token')

        try:
            token = AccessToken(access_token)
            if token:
                return Response({
                    'state': 200,
                    'msg': '退出成功',
                    'data': True
                })
            else:
                return Response({
                    'state': 200,
                    'msg': '无token，退出成功',
                    'data': True
                })
        except Exception as e:
            return Response({
                'state': 200,
                'msg': f'信息：{e}，无效token，退出成功',
                'data': True
            })


@api_view(['POST'])
def upload_avatar(request):
    img_file = request.FILES.get('file')
    user_name = request.POST.get('username')
    password = request.POST.get('password')
    repassword = request.POST.get('repassword')
    image_url = ''

    if img_file:
        image_file = request.FILES['file']
        # 生成唯一文件名
        suffix = image_file.name.split('.')[-1]
        filename = f"{uuid.uuid4()}.{suffix}"
        # 保存文件到 media/uploads/images/
        file_path = os.path.join(filename)
        default_storage.save(file_path, image_file)

        # 构建访问URL（确保你的Django配置了正确的MEDIA_URL）
        image_url = f"{request.scheme}://{request.get_host()}/media/{file_path}"

    if user_name and password and repassword:
        if password == repassword:
            avatar = f'/media{image_url.split('media')[-1]}'
            # 创建用户
            user = User.objects.create_user(
                username=user_name,
                password=password,
                avatar=avatar
            )
            user_serializer = UserSerializer(user)
            return Response({
                'state': 200,
                'msg': '注册成功',
                'data': {
                    'user': user_serializer.data,
                    'success': True,
                }
            })
        else:
            return Response({
                'state': 400,
                'msg': '两次密码不一致',
                'data': {
                    'success': False,
                }
            }, status=request.status.HTTP_400_BAD_REQUEST)

    return Response({
        'state': 400,
        'msg': '无效请求'
    }, status=request.status.HTTP_400_BAD_REQUEST)
